
package Gui;

import Oracle.OracleMethods;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;


/**
 *
 * @author Alonso
 */
public class PagosGUI extends javax.swing.JDialog {

    private SimpleDateFormat fecha = new SimpleDateFormat("dd/MM/yyyy");
    String factura = "";
    int acumulado = 0;
    int monto = 0;
    
    /** Creates new form PagosGUI */
    public PagosGUI(java.awt.Frame parent, boolean modal, String factura, String monto) throws SQLException {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        llenarTablaPagos(factura);
        this.factura = factura;
        this.monto = Integer.parseInt(monto);
    }

    //--------------------LLENAR TABLE-----------------------------------------
    
    private void llenarTablaPagos(String factura) throws SQLException{
        DefaultTableModel table = new DefaultTableModel();
        table.addColumn("Id Number");
        table.addColumn("Fecha");
        table.addColumn("Monto");
        acumulado = 0;
        
        Connection conexion = OracleMethods.oracleConnection();
        Statement sentencia = conexion.createStatement();
        ResultSet resultado = sentencia.executeQuery("SELECT * FROM ao_pago WHERE factura_pk_fk = " + factura);
        
         while(resultado.next()) { 
            Vector row = new Vector();
            row.add(resultado.getString("Pago_pk"));
            row.add(resultado.getString("fecha_pago"));
            row.add(resultado.getString("monto"));
            acumulado = acumulado + resultado.getInt("monto");
            table.addRow(row);
         }
            
            this.tablePagos.setModel(table);
            this.tablePagos.setVisible(true);
            
            sentencia.close();
            resultado.close();
            conexion.close();
    }
    
    //-----------------------------VALIDACIONES---------------------------------
    
    private boolean pagoValido(int monto){
        if( (acumulado + Integer.parseInt(textMonto.getText())) > monto)
            return false;
        else
            return true;
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel15 = new javax.swing.JPanel();
        jScrollPane9 = new javax.swing.JScrollPane();
        tablePagos = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        textMonto = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        buttonRegistrar = new javax.swing.JButton();
        buttonEditar = new javax.swing.JButton();
        buttonBorrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pagos");

        jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        tablePagos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Fecha", "Monto"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablePagos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablePagosMouseClicked(evt);
            }
        });
        jScrollPane9.setViewportView(tablePagos);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Monto");

        jTextField1.setText("jTextField1");

        textMonto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        textMonto.setEnabled(false);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Bs");

        javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
        jPanel15.setLayout(jPanel15Layout);
        jPanel15Layout.setHorizontalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel15Layout.createSequentialGroup()
                        .addGap(116, 116, 116)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2))
                    .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel15Layout.setVerticalGroup(
            jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        buttonRegistrar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        buttonRegistrar.setText("Registrar Pago");
        buttonRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRegistrarActionPerformed(evt);
            }
        });

        buttonEditar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        buttonEditar.setText("Editar Pago");
        buttonEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEditarActionPerformed(evt);
            }
        });

        buttonBorrar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        buttonBorrar.setText("Borrar Pago");
        buttonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBorrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel15, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonBorrar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                        .addComponent(buttonRegistrar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)
                        .addComponent(buttonEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonBorrar, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonRegistrar, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void tablePagosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablePagosMouseClicked
     
}//GEN-LAST:event_tablePagosMouseClicked

private void buttonRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRegistrarActionPerformed
if(buttonRegistrar.getText().equals("Registrar Pago")){
    //Desactivamos la navegacion a otras pantallas, botones y activamos los texts
    textMonto.setEnabled(true);
    textMonto.setText("");
    buttonRegistrar.setText("Confirmar");
    buttonEditar.setEnabled(false);
    buttonBorrar.setEnabled(false);
       
}
else{  
    if(pagoValido(monto) == false){
        JOptionPane.showMessageDialog(this, "El monto acumulado es mayor al monto de la factura");
        return;
    }
    
    
    //Activamos la navegacion a otras pantallas, botones y desactivamos los texts
    textMonto.setEnabled(false);
    buttonRegistrar.setText("Registrar Pago");
    buttonEditar.setEnabled(true);
    buttonBorrar.setEnabled(true);
    
    try{
    Connection con = OracleMethods.oracleConnection();
    Statement sentencia = con.createStatement();
    Date date = new Date();
    sentencia.executeQuery("INSERT INTO ao_pago (pago_pk, factura_pk_fk, monto, fecha_pago) "
                            + "VALUES (pago_pk.nextval,"
                            + "" + factura + " ,"
                            + "'" + textMonto.getText() + "' ,"
                            + "'" + fecha.format(date) + "' )");
    
    sentencia.close();
    con.close();
    
    }
    catch(SQLException e){
        System.out.println("LLene todos los campos");
        JOptionPane.showMessageDialog(this, "SQL Error");
        Logger.getLogger(BaseDatosGUI.class.getName()).log(Level.SEVERE, null, e);
        return;
    }
    
    JOptionPane.showMessageDialog(this, "Registro Exitoso");
    try {
        llenarTablaPagos(factura);
    } catch (SQLException ex) {
        Logger.getLogger(BaseDatosGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}//GEN-LAST:event_buttonRegistrarActionPerformed

private void buttonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBorrarActionPerformed
try {
        Connection con = OracleMethods.oracleConnection();
        Statement sentencia = con.createStatement(); 
        int row = this.tablePagos.getSelectedRow();
        String idPago = (String) this.tablePagos.getModel().getValueAt(row, 0).toString();
        sentencia.executeQuery("DELETE FROM ao_pago WHERE pago_pk = '" + idPago + "'");
        llenarTablaPagos(factura);
        
        sentencia.close();
        con.close();
        
    } catch (SQLException ex) {
        Logger.getLogger(BaseDatosGUI.class.getName()).log(Level.SEVERE, null, ex);
    }   
}//GEN-LAST:event_buttonBorrarActionPerformed

String idPago = "";
private void buttonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEditarActionPerformed
if(buttonEditar.getText().equals("Editar Pago")){
    //Desactivamos la navegacion a otras pantallas, botones y activamos los texts
    int row = this.tablePagos.getSelectedRow();
    idPago = (String) this.tablePagos.getModel().getValueAt(row, 0).toString();
    textMonto.setEnabled(true);
    textMonto.setText("");
    buttonEditar.setText("Confirmar");
    buttonRegistrar.setEnabled(false);
    buttonBorrar.setEnabled(false);
       
}
else{  
    if(pagoValido(monto) == false){
        JOptionPane.showMessageDialog(this, "El monto acumulado es mayor al monto de la factura");
        return;
    }
    //Activamos la navegacion a otras pantallas, botones y desactivamos los texts
    textMonto.setEnabled(false);
    buttonEditar.setText("Editar Pago");
    buttonRegistrar.setEnabled(true);
    buttonBorrar.setEnabled(true);
    System.out.println(idPago);
    
    try{
    Connection con = OracleMethods.oracleConnection();
    Statement sentencia = con.createStatement();
    Date date = new Date();
    sentencia.executeQuery("UPDATE ao_pago SET monto = "
                            + "'" + textMonto.getText() + "'"
                            + "WHERE pago_pk = '" + idPago + "'");
    
    sentencia.close();
    con.close();
    
    }
    catch(SQLException e){
        System.out.println("LLene todos los campos");
        JOptionPane.showMessageDialog(this, "SQL Error");
        Logger.getLogger(BaseDatosGUI.class.getName()).log(Level.SEVERE, null, e);
        return;
    }
    
    JOptionPane.showMessageDialog(this, "Edicion Exitosa");
    try {
        llenarTablaPagos(factura);
    } catch (SQLException ex) {
        Logger.getLogger(BaseDatosGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}//GEN-LAST:event_buttonEditarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PagosGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PagosGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PagosGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PagosGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    PagosGUI dialog = new PagosGUI(new javax.swing.JFrame(), true,"","");
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                        @Override
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                        }
                    });
                    dialog.setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(PagosGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBorrar;
    private javax.swing.JButton buttonEditar;
    private javax.swing.JButton buttonRegistrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JScrollPane jScrollPane9;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTable tablePagos;
    private javax.swing.JTextField textMonto;
    // End of variables declaration//GEN-END:variables
}
